// pages/mine/find/answer/answer.js
var app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    swiperList: [{
      type: 'image',
      url: 'http://m.qpic.cn/psb?/V10uH3z53mPeWp/EWGDmxQMKaDbgQRa3VUpQTQnn4439CkpFYDH*LlhN4E!/b/dL8AAAAAAAAA&bo=gAKJAYACiQECNxM!&rf=viewer_4'
    }, {
      id: 0,
      type: 'image',
      url: 'http://m.qpic.cn/psb?/V10uH3z53mPeWp/sWUbBhPUT8JOFdJb90UAQp6We1u4TUsT3PepovK1Org!/b/dFABAAAAAAAA&bo=AASpAgAEqQIRBzA!&rf=viewer_4'
    }],
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    is_show: false,
    userNum: 9999,
    is_share: false,
    hidden: true,
    prurl: '',
    rest_num: 0,
    is_load:true,
    invite:'',
    is_invite:0
  },
  hideShare() {
    this.setData({
      is_share: false,
      hidden: true
    })
  },
  toShare() {
    this.setData({
      is_share: true,
    })
  },
  bindGetUserInfo(e) {
    var that = this;
    that.onLoad()
    if (e.detail.userInfo) {
      console.log(e.detail.userInfo.nickName)
      app.globalData.userInfo = e.detail.userInfo
      wx.login({
        success: res => {
          // 发送 res.code 到后台换取 openId, sessionKey, unionId
          wx.request({
            url: app.globalData.url + 'user/code',
            data: {
              code: res.code,
              nick: e.detail.userInfo.nickName,
              avatar: e.detail.userInfo.avatarUrl,
              invite: that.data.invite
            },
            method: "POST",
            header: {
              'content-type': 'application/json'
            },
            success: function(res) {
              app.globalData.openid = res.data.data.openid //返回openid
              app.globalData.user_id = res.data.user_id
              console.log("------user_id------")
              console.log(res.data.user_id)
              that.getRestNum()
            }
          })
        }
      })
    }
  },
  getRestNum() {
    var that = this
    wx.request({
      url: app.globalData.url + 'rank/rest/' + app.globalData.user_id, // 仅为示例，并非真实的接口地址
      data: {},
      method: "GET",
      header: {
        'content-type': 'application/json' // 默认值
      },
      success(res) {
        console.log(res.data)
        that.setData({
          rest_num: res.data.data.today_num,
          is_invite: res.data.data.is_invite
        })
      }
    })
  },
  updateRestNum() {
    var that = this
    wx.request({
      url: app.globalData.url + 'rank/' + app.globalData.user_id, // 仅为示例，并非真实的接口地址
      data: {},
      method: "PUT",
      header: {
        'content-type': 'application/json' // 默认值
      },
      success(res) {
        console.log(res.data)
        that.setData({
          rest_num: that.data.rest_num - 1
        })
      }
    })
  },
  toIndex() {
    var that = this
    //this.getRestNum()
    if(that.data.is_invite)
    {
      wx.showModal({
        title: '提示',
        content: '今日有效答题次数剩余：∞，邀请新同学可获得10新币哦~' ,
        success: function (res) {
          if (res.confirm) {
            wx.navigateTo({
              url: './index/index'
            })
          } else {
            console.log('用户点击取消')
          }
        }
      })
    }
    else if (that.data.rest_num > 0) {
      wx.showModal({
        title: '提示',
        content: '今日有效答题次数剩余：' + that.data.rest_num ,
        success: function(res) {
          if (res.confirm) {
            that.updateRestNum()
            wx.navigateTo({
              url: './index/index'
            })
          } else {
            console.log('用户点击取消')
          }
        }
      })
    } else {
      that.updateRestNum()
      wx.showModal({
        title: '提示',
        content: '今日有效答题次数已用完，继续答题将不计分，邀请新同学可获得无限次数哦~',
        success: function (res) {
          if (res.confirm) {
            that.updateRestNum()
            wx.navigateTo({
              url: './index/index'
            })
          } else {
            console.log('用户点击取消')
          }
        }
      })
    }



  },
  toRank() {
    wx.navigateTo({
      url: './rank/rank'
    })
  },
  toComment() {
    wx.navigateTo({
      url: '/pages/topic/detail/detail?topic={"choice1":"全球某工商生日快乐","choice2":"浙工商越办越好","id":1,"is_show":true,"time":null,"title":"庆祝浙商大108华诞","type":2,"user_id":null}'
    })
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    
    var that = this;
    //that.down()
    if (options != null)
    {
      console.log("------options------")
      console.log(options)
      that.setData({
        invite: options.invite
      })
      console.log(options.invite)
    }
    that.setData({
      is_load:false,
      
    })
    wx.login({
      success(res) {
        if (res.code) {
          // 发起网络请求
          wx.request({
            url: app.globalData.url + 'user/code/' +res.code,
            data: {
            },
            header:{
              'content-type': 'application/json'
            },
            success: function (res) {
                console.log('----user-----')
                console.log(res.data.user_id)
                app.globalData.user_id=res.data.user_id
                that.getRestNum()
            },
          })
        } else {
          console.log('登录失败！' + res.errMsg)
        }
      }
    })
    wx.getSetting({
      
      success(res) {
        if (res.authSetting['scope.userInfo']) {
          // 已经授权，可以直接调用 getUserInfo 获取头像昵称
          wx.getUserInfo({
            success(res) {
              console.log(res.userInfo)
              that.setData({
                is_load: true
              })
            }
          })
          that.getRestNum()
          that.setData({
            is_show: false
          })
        } else {
          that.setData({
            is_load: true,
            is_show: true
          })
        }
      }
    })
    that.getUserCount()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {
    this.onLoad()
    wx.stopPullDownRefresh();
  },
  //获取答题人数
  getUserCount() {
    var that = this
    wx.request({
      url: app.globalData.url + 'rank/all', // 仅为示例，并非真实的接口地址
      data: {},
      method: "GET",
      header: {
        'content-type': 'application/json' // 默认值
      },
      success(res) {
        console.log(res.data)
        that.setData({
          userNum: res.data.data
        })
      }
    })

  },
  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function(res) {
    var that = this
    if (res.from === 'button') {
      // 来自页面内转发按钮
      console.log(res.target)
      that.setData({
        is_share: false
      })
    }
    return {
      title: '答题知校史，自信商大人',
      path: 'pages/mine/find/answer/answer?invite='+app.globalData.user_id,
      imageUrl: 'http://m.qpic.cn/psb?/V10uH3z53mPeWp/7JipVadPBsDOe3brKK.GDj3o1DKQogLMHj9.o7B*1ak!/b/dFABAAAAAAAA&bo=AAUABAAFAAQDByI!&rf=viewer_4', //自定义图片路径，可以是本地文件路径、代码包文件路径或者网络图片路径。支持PNG及JPG。显示图片长宽比是 5:4。
      
    }
  },
  share: function() {
    var that = this
    wx.showLoading({
      title: '努力生成中...'
    })
    wx.canvasToTempFilePath({
      x: 0,
      y: 0,
      width: 545,
      height: 771,
      destWidth: 545,
      destHeight: 771,
      canvasId: 'shareImg',
      success: function(res) {
        console.log(res.tempFilePath);
        that.setData({
          prurl: res.tempFilePath,
          hidden: false
        })
        wx.hideLoading()
      },
      fail: function(res) {
        console.log(res)
      }
    })
  },
  down() {
    let promise1 = new Promise(function(resolve, reject) {
      wx.getImageInfo({
        src: 'https://api.bangstuhelp.com/news/img/qrcode.png',
        success: function(res) {
          console.log(res)
          resolve(res);
        }
      })
    });
    let promise2 = new Promise(function(resolve, reject) {
      wx.getImageInfo({
        src: 'https://api.bangstuhelp.com/news/img/qrbg.png',
        success: function(res) {
          console.log(res)
          resolve(res);
        }
      })
    });
    Promise.all([
      promise1, promise2
    ]).then(res => {
      console.log(res)
      const ctx = wx.createCanvasContext('shareImg')
      //主要就是计算好各个图文的位置

      ctx.drawImage(res[1].path, 0, 0, 489, 771)
      ctx.drawImage(res[0].path, 380, 665, 80, 80)
      console.log(res[0].path)
      // ctx.setTextAlign('center')
      // ctx.setFillStyle('#ffffff')
      // ctx.setFontSize(22)
      // ctx.fillText('分享文字描述1', 545 / 2, 130)
      // ctx.fillText('分享文字描述2', 545 / 2, 160)

      ctx.stroke()
      ctx.draw()
    })
  },
  save: function() {
    var that = this
    //生产环境时 记得这里要加入获取相册授权的代码
    wx.saveImageToPhotosAlbum({
      filePath: that.data.prurl,
      success(res) {
        wx.showModal({
          content: '图片已保存到相册，赶紧晒一下吧~',
          showCancel: false,
          confirmText: '好哒',
          confirmColor: '#72B9C3',
          success: function(res) {
            if (res.confirm) {
              console.log('用户点击确定');
              that.setData({
                hidden: true,
                is_share: false
              })
            }
          }
        })
      }
    })

  }
})